from django import template
from django.utils.safestring import mark_safe
from string import join

register = template.Library()

@register.filter(name='match')
def match(value, format_options=1):
    """
    format_options je bitmaska:
    pos 0 - bold winner
    pos 1 - absolute URL
    pos 2 - razmak izmedju igraca (crta ili URL detaljno)
    """
    if (format_options & 2) == 2:
        absolute_url = "http://sport.mdcs.rs"
    else:
        absolute_url = ""
    table = "<table><tbody><tr><td style=\"width:300px; text-align: center;\">"
    first = True
    for user in value.home.all():
        if not first:
            table += "<br/>"
        css_class = get_user_class(user)
        tempstr = "<a class=\"%s\" href=\"%s/mdcs/user/%d/\">%s %s</a>" % (css_class, absolute_url, user.id, user.user.first_name, user.user.last_name)
        if (format_options & 1) == 1 and value.winner == 1:
            tempstr = "<b>" + tempstr + "</b>" 
        table += tempstr
        first = False
    if (format_options & 4) == 4:
        sep = "&mdash;"
    else:
        sep = '(<a href="%s/mdcs/match/%d/">detaljno<a/>)' % (absolute_url, value.id)
    table += "</td><td>%s</td><td style=\"width:300px; text-align: center;\">" % sep
    first = True
    for user in value.away.all():
        if not first:
            table += "<br/>"
        css_class = get_user_class(user)
        tempstr = "<a class=\"%s\" href=\"%s/mdcs/user/%d/\">%s %s</a>" % (css_class, absolute_url, user.id, user.user.first_name, user.user.last_name)
        if (format_options & 1) == 1 and value.winner == 3:
            tempstr = "<b>" + tempstr + "</b>"
        table += tempstr
        first = False
    table += "</td></tr></tbody></table>"

    return mark_safe(table)

def get_user_class(user):
    if user.user.is_active:
        if user.is_mdcs:
            return "user"
        else:
            return "user_notmdcs"
    else:
        if user.is_mdcs:
            return "user_notactive"
        else:
            return "user_notmdcs_notactive"